package top.atluofu.luofuecommerce.search.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.atluofu.common.to.es.SkuEsModel;
import top.atluofu.luofuecommerce.search.config.ElasticSearchConfig;
import top.atluofu.luofuecommerce.search.constant.EsConstant;
import top.atluofu.luofuecommerce.search.service.ProductSaveServie;

import java.io.IOException;
import java.util.List;

/**
 * @ClassName: ProductSaveServiceImpl
 * @description: TODO
 * @author: 有罗敷的马同学
 * @datetime: 2022Year-11Month-15Day-21:12
 * @Version: 1.0
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveServie {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) {
        // 1. save mapping

        // 2. save data
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String s = JSON.toJSONString(skuEsModel);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk;
        try {
            bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // todo 错误处理
        log.error("出错了");
        return !bulk.hasFailures();

    }
}
